#include"comm.h"
union semun {
    int  val;    /* Value for SETVAL */
    struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
    unsigned short  *array;  /* Array for GETALL, SETALL */
    struct seminfo  *__buf;  /* Buffer for IPC_INFO*/
}; 

static int comm_get_sem(int msems,int flag)
{
	key_t _sem_key=ftok(_PATH_,_PROJ_ID);
	if(_sem_key<0)
	{
		perror("ftok");
		return -1;
	}
	int sem_id=semget(_sem_key,msems,flag);
	if(sem_id<0)
	{
		return -1;
	}
	return sem_id;
	
}
int creat_sem(int nsems)
{
	umask(0);
	return comm_get_sem(nsems,IPC_CREAT|IPC_EXCL|0666);
}

int get_sem()
{
	return comm_get_sem(0,IPC_CREAT);
}
int init_sem(int semid,int whitch)
{
	union semun _semnu;
	_semnu.val=1;
	int ret = semctl(semid,whitch,SETVAL,_semnu);
	return ret;
}
static int sem_op(int semid,struct sembuf *sops,unsigned nsops)
{
		return semop(semid,sops,nsops);
}
hello
int p_sem_op(int semid,int which)
{	
	struct	sembuf sem;
hello
	sem.sem_op=-1;
	sem.sem_num=which;
	sem.sem_flg=SEM_UNDO;
	return sem_op(semid,&sem,1);
}

int v_sem_op(int semid,int which)
{
	struct sembuf sem;
	sem.sem_op=1;
	sem.sem_num=which;
	sem.sem_flg=SEM_UNDO;
	return sem_op(semid,&sem,1);
}
int destroy_sem(int sem_id)
{
	int ret =semctl(sem_id,0,IPC_RMID,NULL);
		
	if(ret <0){
			return -1;
		}
	return 0;
}
